package logback;

import java.io.File;

public class DeleteLog {
	
	public static int moveFile(File afile, String Path2) {
		try {
			if (afile.renameTo(new File(Path2))) {
				return 0;
			} else {
				return -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}
	
	public static String getNewFilePath(String filePath, String fileName) {
		
		File tmpDir = new File(filePath + File.separator + "old_log");
		if (!tmpDir.exists()) {
			tmpDir.mkdirs();
		}
		
		int i = 0;
		for (;;) {
			String newFileName = filePath + File.separator + "old_log" + File.separator + fileName + "_" + Integer.toString(i);
			File tmpFile = new File(newFileName);
			if (!tmpFile.exists()) {
				return newFileName;
			}
			i++;
		}
	}
	
	public static boolean safetyDelete(File file) {
		String fileName = file.getName();
		String parentPath = file.getParent();
		String newFilePath = getNewFilePath(parentPath, fileName);
		System.out.println(newFilePath);
		
		moveFile(file, newFilePath);
		
		File newFile = new File(newFilePath);
		if (newFile.delete()) {
			System.out.println(file.getName() + " is deleted!");
			return true;
		} else {
			System.out.println("Delete operation is failed.");
			return false;
		}
		
	}
	public static void main(String[] args) {
		try {
			String testFilePath = "d:\\luan.txt";
			safetyDelete(new File(testFilePath));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
